package com.coin900.coin.base.config;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

/**
 * Unibon
 * <p/>
 * Copyright (c) 2012 YouPeng ValueSoft Inc., All rights reserved.
 * <p/>
 * This software is the confidential and proprietary information of
 * ValueSoft Company. ("Confidential Information").  You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into
 * with ValueSoft.com.
 * <p/>
 * Revision History
 * Date      		Programmer       Notes
 * 2014/12/26   	     stone		     Initial
 * *********************************************************************
 */
@Component
public class ServerData implements InitializingBean {
    /**
     * ip地址
     */
    private String hostAddress;
    /**
     * 外网ip:port
     */
    private String wanAddress;

    @Override
    public void afterPropertiesSet() throws Exception {
        this.hostAddress = this.getLanIp("192.168.");
        if(this.hostAddress==null){
            this.hostAddress = this.getLanIp("172.");
        }

//        File file = new File("/home/res/eduos/ip.txt");
//        if (file.exists()) {
//            FileReader fr = new FileReader(file);
//            BufferedReader br = new BufferedReader(fr);
//            while ((wanAddress = br.readLine()) != null) {
//                break;
//            }
//            fr.close();
//        }else{
//            wanAddress = System.getenv("WAN_IP");
//        }

        wanAddress = System.getenv("WAN_IP");
    }

    private String getLanIp(String prefix) throws SocketException {
        String lanIp = null;
        Enumeration<NetworkInterface> n = NetworkInterface.getNetworkInterfaces();
        boolean ipDone = false;
        for (; n.hasMoreElements(); ) {
            NetworkInterface e = n.nextElement();
            Enumeration<InetAddress> a = e.getInetAddresses();
            for (; a.hasMoreElements(); ) {
                InetAddress addr = a.nextElement();
                if (addr.getHostAddress().contains(prefix)) {
                    lanIp = addr.getHostAddress();
                    ipDone = true;
                    break;
                }
            }
            if (ipDone) {
                break;
            }
        }
        return lanIp;
    }

    public String getHostAddress() {
        return hostAddress;
    }

    public void setHostAddress(String hostAddress) {
        this.hostAddress = hostAddress;
    }

    public String getWanAddress() {
        return wanAddress;
    }

    public void setWanAddress(String wanAddress) {
        this.wanAddress = wanAddress;
    }
}
